import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'
import HomeView from '@/views/HomeView.vue'
import AdminPermissionGroupView from '@/views/AdminPermissionGroupView.vue'
import AdminPermissionManagementView from '@/views/AdminPermissionManagementView.vue'
import MenuManagementView from '@/views/MenuManagementView.vue'
import GoodsManagementView from '@/views/GoodsManagementView.vue'
import CategoryManagementView from '@/views/CategoryManagementView.vue'
import ChatManagementComputerView from '@/views/ChatManagementComputerView.vue'
import ChatManagementMobileView from '@/views/ChatManagementMobileView.vue'

Vue.use(VueRouter)
// 解决编程式路由往同一地址跳转时会报错的情况
const originalPush = VueRouter.prototype.push;
const originalReplace = VueRouter.prototype.replace;

// push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

//replace
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalReplace.call(this, location, onResolve, onReject);
  return originalReplace.call(this, location).catch(err => err);
};

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },

  {
    path: '/home',
    name: 'Home',
    component: HomeView
  },
  {
    path: '/permission/admin',
    name: 'AdminPermissionManagement',
    component: AdminPermissionManagementView
  },
  {
    path: '/permission/admin-group',
    name: 'AdminPermissionGroup',
    component: AdminPermissionGroupView
  },
  {
    path: '/menu-management',
    name: 'MenuMangement',
    component: MenuManagementView
  },
 
  {
    path: '/goods-management',
    name: 'GoodsManagement',
    component: GoodsManagementView
  },
  {
    path: '/category-management',
    name: 'CategoryManagement',
    component: CategoryManagementView
  },
  {
    path: '/chat-management-computer',
    name: 'ChatManagementComputer',
    component: ChatManagementComputerView,
  },
  {
    path: '/chat-management-mobile',
    name: 'ChatManagementMobile',
    component: ChatManagementMobileView
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior(to, from, saveNotRequired) {
    //始终滚到顶部
    return { x: 0, y: 0 }
  }
})

// 全局前置守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const publicPages = ['/login']; // 不需要登录即可访问的页面路径
  const authRequired = !publicPages.includes(to.path);
  const token = localStorage.getItem('token'); // 从 localStorage 获取 token

  if (authRequired && !token) {
    // 如果需要授权但没有token，重定向到登录页
    next('/login');
  } else {
    // 如果是登录页，且已经有token，重定向到主页（可选，避免重复登录）
    if (to.path === '/login' && token) {
       next({ path: '/' });
    } else {
       next(); // 正常跳转
    }
  }
});

export default router
